package ru.nosport.matrixaria.core;

import org.apache.commons.configuration.Configuration;
import java.util.*;

/**
 * User: vfabr
 * Date: 25.09.2006
 * Time: 15:52:14
 */
class ModuleShortcut {
	private Class instanceClass;
	private String instanceName;
	private Map<String,String> dependences;
	private Configuration config;

	/**
	 * Constructor.
	 *
	 * @param _config configuration for instance being loaded
	 * @param _className instance class name
	 * @throws InitException
	 */
	public ModuleShortcut(Configuration _config, String _className) throws InitException {
		this.dependences = new HashMap<String,String>(10, 1.7f);
		this.instanceName = _config.getString("[@name]");
		this.setInstanceClass(_className);
		this.makeMap(_config.subset("dependences"));
		this.config = _config.subset("parameters");
		this.config.addProperty("registryInstanceName", this.instanceName);
	}

	/**
	 * Returns class object for the instance.
	 *
	 * @return instance class object
	 */
	public Class getInstanceClass() {
		return this.instanceClass;
	}

	/**
	 * Returns configuration used in instance creation process.
	 *
	 * @return configuration object
	 */
	public Configuration getConfig() {
		return config;
	}

	/**
	 * Make map dependences.
	 *
	 * @param _config
	 */
	private void makeMap(Configuration _config) throws InitException {
		List deps = _config.getList("dependence[@name]");
		for (int i=0; i < deps.size(); i++) {
			String key = _config.getString("dependence(" + i + ")[@name]");
			String val = _config.getString("dependence(" + i + ")");
			if(! this.dependences.containsKey(key)) {
				this.dependences.put(key, val);
			} else {
				throw new InitException("Duplicate dependence name. Name - " + key + ", value - " + val);
			}
		}
	}

	/**
	 * Set instance name.
	 *
	 * @param _name instance name
	 */
	private void setInstanceClass(String _name) throws InitException {
		try {
			this.instanceClass = Class.forName(_name);
		} catch(ClassNotFoundException _ex) {
			throw new InitException("Class " + _name + " not found.");
		}
	}

	/**
	 * Return instance name.
	 *
	 * @return instance name.
	 */
	public String getInstanceName() {
		return this.instanceName;
	}

	/**
	 *
	 * @return Map of dependences
	 */
	public Map getDependences() {
		return this.dependences;
	}

	/**
	 * Checks whether module depends on another (with class check)
	 *
	 * @param key
	 * @param value
	 * @return true if module depenedces contains entry with the given key (instance name) and value (class name) 
	 */
	public boolean checkDependsOn(String key, String value){
		return this.dependences.containsKey(key) && this.dependences.get(key).equals(value);
	}
}
